﻿

using IotClientService.Models.Lg;
using IotClientService.Services;
using IotContract.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Extensions;

namespace IotClientService.Handles.lgs;
/// <summary>
/// 组盘
/// 电池装载
/// 1. 933：上位机发送托盘到达 934:FMS 回复此托盘是否 NG
/// 2. 905（S）：上位机告知作业开始 906:FMS 应答
/// 3. 901 上位机每次抓取 4 个电池告知 902：FMS 判断电池是否数据异常 （一直重复到 48 个电池装满）
/// 4. 905（E）：上位机告知作业结束并且告知托盘码，电池数量和电池码（电池与托盘绑定数据） 906：FMS 应答
/// 5. 937：上位机告知托盘出去 938：FMS 应答
/// </summary>
public class LgHandleAssemble:LgHandleBase
{
    public LgHandleAssemble(ILgApiService lgCallApiService) : base(lgCallApiService)
    {
    }

    public override IotEquipType EquipType { get; set; } = IotEquipType.AEB;
    /// <summary>
    /// 处理消息 
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public override async Task<bool> HandleMsg(LgMsgInfo msg)
    {
        string replyCmd = string.Empty;
        switch (msg.Command)
        {
            // 作业结果数据报告 
            case "901":
                replyCmd = "902";
                await Handle901(msg, replyCmd);
                break;
            // 作业开始/结束报告，上位机报告
            case "905":
                replyCmd = "906";
               await Handle905(msg, replyCmd);
                break;
            // 设备状态报告指示回应，主动发送909获取状态
            case "910":
               await Handle910(msg, "910");
                // send 833 

                break;
            // 设备状态报告，待机状态变设备运行状态或设备运行状态变设备待机
            case "913":
               await Handle913(msg, "913");
                break;
            // 作业mode报告，设备模式切换时告知，如自动模式切换手动模式，反过来也是一样
            case "917":
                replyCmd = "918";
               await Handle917(msg, replyCmd);
                break;
            // 通信状态报告邀请，上位机和 FMS 相互连接状态
            case "925":
                replyCmd = "926";
               await Handle925(msg, replyCmd);
                break;
            // 通信状态报告回应
            case "926":
               await Handle926(msg, "926");
                break;
            // Tray Load报告 上位机告知 FMS 托盘到达
            case "933":
                replyCmd = "934";
               await Handle933(msg, replyCmd);
                break;
            // 托盘出库完成报告，上位机告知托盘要出库
            case "937":
                replyCmd = "938";
               await Handle937(msg, replyCmd);
                break;
            // 未知命令,错误
            case "981":
               await Handle981(msg, "981");
                break;
            // 设备Trouble报告，设备发生异常告知FMS
            case "985":
               await Handle985(msg, "985");
                break;
          

            // 设置时间指示
            case "999":
               await Handle999(msg, replyCmd);
                break;
            default:
                // send 981
               await Handle981(msg, "981");
                break;
        }
        return true;
    }
    /// <summary>
    /// 作业结果数据报告，每次抓取 4 个电池报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle901(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 托盘码
        string tray = msg.Message.Substring(18, 10);
        int cellCnt = 2;
        if(msg.Message.Length > 90)
        {
            cellCnt = 4;
        }
        // 抓取的电池码4个
        string cellCodes = msg.Message.Substring(38, 24*cellCnt);

        List<string> cells = new List<string>();
        for(int i = 0; i < cellCnt; i++)
        {
            cells.Add(cellCodes.Substring(i * 24, 24));
        }

       var result=await Api.CommitAssembleResult(new Models.Lg.Remote.LgCellResultRequest
        {
            EquipNum = Equip.Num,
            Cells = cells,
            Tray = tray,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType
        });
        // 0:OK 1:NG
        int ret = 0;
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
        else
        {
            ret = result.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }

        // 4*4=16位
        string ngCodes = string.Empty ;

        // 19017 没有作业开始的托盘
        // 19018 不是不良
        // 19000 处理错误
        if (result.Result.IsNotNull() && result.Result.NgCodes.IsNotNull())
        {
            foreach (var cell in result.Result.NgCodes)
            {
                ngCodes += cell.PadLeft(4, '0');
            }
        }

        sendMsg.Body = $"{ret.ToString().PadLeft(cellCnt, '0')}{ngCodes}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);


    }
  

    /// <summary>
    /// 作业开始/结束报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle905(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
       
        // 托盘
        string tray = msg.Message.Substring(18, 10);
        // 电池数量
        var cellCount = msg.Message.Substring(38, 2);
        // S:作业开始  E:作业完成
        string status = msg.Message.Substring(40 + 24 * 16, 1);
        int trayChannel = 16;
        if (msg.Message.Length > 430)
        {
            status = msg.Message.Substring(40 + 24 * 48, 1);
            trayChannel = 48;
        }
       
        // 电池码 24*48
        var cells = new Dictionary<int, string>();
        if (status == "E")
        {
            for (int i = 0; i < trayChannel; i++)
            {
                string cell = msg.Message.Substring(40 + i * 24, 24);
                if (cell.Trim().IsNotNullOrEmpty())
                {
                    cells.Add(i + 1, msg.Message.Substring(40 + i * 24, 24));
                }
            }
        }

        var result = await Api.CommitAssembleReport(new Models.Lg.Remote.LgAssembleReportRequest
        {
            EquipNum = Equip.Num,
            EquipType = this.EquipType,
            ProgramType = Equip.ProgramType,
            CellCount = cellCount,
            Tray = tray,
            Cells = cells,
            Status = status
        });
        // 0:ok 1:ng
        int ret = 0;
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
        else
        {
            ret = result.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }


        var ngCode = result.Result?.NgCodes?.FirstOrDefault() ?? "0000";
        sendMsg.Body = $"{tray.PadRight(20, '0')}{ret}{ngCode}{status}";
        sendMsg.IsSend = true;
        Equip.Remark = $"tray:{tray}-{status}";
        InvokeSend(sendMsg);

    }

    /// Tray Load报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle933(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,
            
        };
        // 托盘
        var tray = msg.Message.Substring(18, 10);

      
        Equip.Obj = tray;
      
        Equip.Remark = $"tray load:{tray}";



        var result = await Api.CommitAssembleTrayEnter(new Models.Lg.Remote.LgTrayEnterRequest
        {
            EquipType = this.EquipType,
            EquipNum = Equip.Num,
            ProgramType = Equip.ProgramType,
            Tray = tray
        }); ;
        
        int ret = 0;
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
        else
        {
            ret = result.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }

        #region 传输body

        // 0:ok 1:ng  2:bypass 

        // 0001-9999NG
        var ngCode =  result.Result?.NgCodes?.FirstOrDefault() ?? "0000"; 
      
        #endregion
        sendMsg.Body = $"{ret}{ngCode}{tray.PadRight(20,'0')}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);
    }
    /// <summary>
    /// 托盘出库完成报告
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="replyCmd"></param>
    private async Task Handle937(LgMsgInfo msg, string replyCmd)
    {
        var sendMsg = new LgMsgInfo
        {
           
            Direction = 0,
            ObjID = msg.ObjID,
            HasMsg = 0,
            SeqNo = msg.SeqNo,
            Command = replyCmd,

        };
        // 托盘
        var tray = msg.Message.Substring(18, 10);
      
        Equip.Obj = "";

        Equip.Remark = $"tray out:{tray}";


       var result= await Api.CommitAssembleTrayOut(new Models.Lg.Remote.LgTrayOutRequest
        {
           EquipNum=Equip.Num,
            Tray = tray
        });
        int ret = 0;
        if (!result.Success)
        {
            Equip.ExMessage = result.Message;
            ret = 1;
        }
        else
        {
            ret = result.Result?.Ret ?? 1;
        }
        if (ret == 1)
        {
            msg.Body = ret.ToString();
            await Handle981(msg, "981");
            return;
        }

        #region 传输body

        // 937不是空托盘
        // 9002没有获取tray信息

        #endregion
        sendMsg.Body = $"{ret}{tray.PadRight(20,'0')}";
        sendMsg.IsSend = true;
        InvokeSend(sendMsg);
    }
  
    

    
}
